import { create } from 'zustand';
import { persist } from 'zustand/middleware';

const useAuthStore = create(
  persist(
    (set, get) => ({
      // 用户信息
      user: null,
      // 认证token
      token: null,
      // 是否已认证
      isAuthenticated: false,
      // 登录状态
      isLoading: false,

      // 登录
      login: (userData) => {
        set({
          user: userData,
          token: userData.token,
          isAuthenticated: true,
          isLoading: false,
        });
        
        // 将token存储到localStorage（可选，因为persist已经处理了）
        localStorage.setItem('auth_token', userData.token);
      },

      // 登出
      logout: () => {
        set({
          user: null,
          token: null,
          isAuthenticated: false,
          isLoading: false,
        });
        
        // 清除localStorage中的token
        localStorage.removeItem('auth_token');
      },

      // 检查认证状态
      checkAuth: () => {
        const { token } = get();
        if (token) {
          set({ isAuthenticated: true });
          return true;
        }
        return false;
      },

      // 设置加载状态
      setLoading: (loading) => {
        set({ isLoading: loading });
      },

      // 更新用户信息
      updateUser: (userData) => {
        set({ user: { ...get().user, ...userData } });
      },

      // 清除认证状态
      clearAuth: () => {
        set({
          user: null,
          token: null,
          isAuthenticated: false,
          isLoading: false,
        });
        localStorage.removeItem('auth_token');
      },
    }),
    {
      name: 'auth-storage', // 存储的key名称
      partialize: (state) => ({
        user: state.user,
        token: state.token,
        isAuthenticated: state.isAuthenticated,
      }),
    }
  )
);

export default useAuthStore;
